from typing import Any, Dict, Generic, Optional, Type, TypeVar
from tortoise.queryset import QuerySet
from fastapi import HTTPException
from pydantic import BaseModel
from app.core.i18n import t
from app.schemas.common import OrderSchema, PaginationParams, PaginationResult
from app.core.exceptions import APIException
from logging import getLogger

logger = getLogger(__name__)

ModelType = TypeVar("ModelType")
ItemSchemaType = TypeVar("ItemSchemaType", bound=BaseModel)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)


async def filter_query(
    query: QuerySet, filters: Any, special_filter_conditions: Dict[str, Dict[str, Any]] = None
) -> QuerySet:
    """通用查询过滤方法"""
    if not filters:
        return query

    filter_dict = {}
    for field, value in filters.model_dump().items():
        if value is not None:
            if field in (special_filter_conditions or {}):
                filter_dict.update(special_filter_conditions[field])
            else:
                filter_dict[field] = value

    return query.filter(**filter_dict) if filter_dict else query
